# !/usr/bin/env python
# -*- coding:utf-8 -*-
# @FileName: demo.py
# @Time    : 2021/7/6 13:57
# @Author  : MaXiaoLong
# -*- coding:utf-8 -*-
# Author: MaXiaoLong
# Data: 2020/10/27 17:47
import os
import requests


def create_nacos_namespace(url, nsName, nsID, nsDesc):
    conn = "http://%s/nacos/v1/console/namespaces" % url

    payload = "namespaceName=%s&namespaceDesc=%s&customNamespaceId=%s" % (nsName, nsDesc, nsID)

    headers = {
        'content-type': "application/x-www-form-urlencoded"
    }

    response = requests.Request(method="POST", url=conn, data=payload, headers=headers)

    print("create namespace %s success" % nsName)

    return response


def uploadConfigTONacos(url, cf_dict):
    if not cf_dict:
        print("配置字典为空")
        return

    path = "http://%s/nacos/v1/cs/configs" % url

    nsName = cf_dict.get("namespacename")
    nsId = cf_dict.get("namespaceid")
    dataId = cf_dict.get("dataid")
    group = cf_dict.get("group")
    filePath = cf_dict.get("localfile")

    if os.path.isfile(filePath):
        with open(filePath, "r", encoding="utf-8") as f:
            content = f.read()
    else:
        content = filePath

    payload = {'tenant': nsId,
               'dataId': dataId,
               'group': group,
               'content': content,
               'type': "xml"}

    response = requests.request("POST", path, data=payload)

    print("success write config xml file to %s %s %s" % (nsName, group, dataId))


if __name__ == '__main__':
    # 需要手工修改的
    url = "{{ hostvars[groups.nacos[0]].ansible_ssh_host }}:{{ nacos.port }}"
    filePath = "{{ br.root }}/conf/{{ nacos.dir }}"

    # ns_list = [
    #     {"namespacename": "BONREE_GLOBAL", "namespaceid": "b1751c5c-13d9-49c0-a6b1-8487f9f46f96",
    #      "dataid": "GLOBAL", "group": "CONFIG_GLOBAL", "localfile": os.path.join(filePath, "global.xml")},
    #     {"namespacename": "BONREE_DATAVIEW", "namespaceid": "2e539b82-ad14-426b-b079-80b227ff4ec9",
    #      "dataid": "DATAVIEW", "group": "CONFIG_DATAVIEW", "localfile": os.path.join(filePath, "DATAVIEW.xml")},
    # ]

    ns_list = [
        {"namespacename": "BONREE_GLOBAL", "namespaceid": "b1751c5c-13d9-49c0-a6b1-8487f9f46f96",
         "dataid": "GLOBAL", "group": "CONFIG_GLOBAL", "localfile": os.path.join(filePath, "{{ nacos.global_file }}")},
    ]

    for ns in ns_list:
        nsDesc = "namespace %s create for dataview" % ns
        nsName, nsID = ns.get("namespacename"), ns.get("namespaceid")
        create_nacos_namespace(url, nsName, nsID, nsDesc)

        uploadConfigTONacos(url, ns)